package com.ipay.wechat.service.impl;

import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ipay.redis.JedisExecutor;
import com.ipay.redis.JedisKeyPrefix;
import com.ipay.utils.RandomStringUtils;
import com.ipay.utils.StringUtil;
import com.ipay.wechat.dao.LoginDao;
import com.ipay.wechat.pojo.UserWechatInfo;
import com.ipay.wechat.pojo.WechatLogin;
import com.ipay.wechat.service.CashiersService;
import com.ipay.wechat.service.LoginService;
import com.ipay.wechat.service.TradeRecordService;
import com.ipay.wechat.service.UserWechatInfoService;
import com.ipay.wechat.util.ExecuteWeChat;
import com.ipay.wechat.util.HttpUtils;
import com.ipay.wechat.util.Utils;

import net.sf.json.JSONObject;

@Service("loginService")
public class LoginServiceImpl implements LoginService {
    private static Logger logger = LoggerFactory
            .getLogger(LoginServiceImpl.class);
    @Autowired
    private LoginDao loginDao;
    @Autowired
    private UserWechatInfoService userWechatInfoService;
    @Autowired
    private TradeRecordService tradeRecordService;
    @Autowired
    private CashiersService cashiersService;
    @Autowired
    private JedisExecutor jedisExe;
    @Autowired
    private UserWechatInfoService uwiService;

    @Override
    public WechatLogin findWechatLogin(String mobilephone) {
        // TODO Auto-generated method stub
        return loginDao.findWechatLogin(mobilephone);
    }

    @Override
    public void insertWechatLogin(String mobilephone, int status,
                                  String openid) {
        // TODO Auto-generated method stub
        WechatLogin wechatLogin = new WechatLogin();
        wechatLogin.setMobilephone(mobilephone);
        wechatLogin.setOpenid(openid);
        wechatLogin.setStatus(status);
        loginDao.insertWechatLogin(wechatLogin);
    }

    @Override
    public WechatLogin findWechatLoginByOpenid(String openid) {
        // TODO Auto-generated method stub
        return loginDao.findWechatLoginByOpenid(openid);
    }

    /**
     * 查询商户下用户信息
     * @param merchantId
     * @return
     */
    @Override
    public List<WechatLogin> findWechatLoginByMerchantId(String merchantId,String codeNo) {
        return loginDao.findWechatLoginByMerchantId(merchantId,codeNo);
    }

    @Override
    @Transactional
    public boolean updateWechatLogin(int status, String mobile, String openid) {
        boolean bool = false;
        WechatLogin login = loginDao.findWechatLogin(mobile);
        if (login == null || StringUtil.isEmpty(login.getMobilephone())) { // 第一次登录
            // TODO Auto-generated method stub
            WechatLogin wechatUpOpenid = new WechatLogin();
            wechatUpOpenid.setOpenid(openid);
            loginDao.updateOpenid(wechatUpOpenid);

            insertWechatLogin(mobile, 1, openid);  //0未登陆，1已登录
            bool = true;
        } else {
            if (StringUtil.isNotEmpty(login.getOpenid())) { //非首次登录
                System.out.println("openid:" + openid + "    login.getOpenid():" + login.getOpenid());
                if (openid.equals(login.getOpenid())) {//手机对应用户openid是不是当前获取到的openid
                    // 将状态修改为已登录
                    WechatLogin wechatLogin = new WechatLogin();
                    wechatLogin.setMobilephone(mobile);
                    wechatLogin.setOpenid(openid);
                    wechatLogin.setStatus(status);
                    loginDao.updateWechatLogin(wechatLogin);
                    bool = true;
                } else {
                    // TODO Auto-generated method stub
                    WechatLogin wechatUpOpenid = new WechatLogin();
                    wechatUpOpenid.setOpenid(openid);
                    loginDao.updateOpenid(wechatUpOpenid);

                    // TODO Auto-generated method stub
                    WechatLogin wechatLogin = new WechatLogin();
                    wechatLogin.setMobilephone(mobile);
                    wechatLogin.setOpenid(openid);
                    wechatLogin.setStatus(status);
                    loginDao.updateWechatLogin(wechatLogin);
                    bool = true;
                }
            } else {
                // TODO Auto-generated method stub
                WechatLogin wechatUpOpenid = new WechatLogin();
                wechatUpOpenid.setOpenid(openid);
                loginDao.updateOpenid(wechatUpOpenid);

                // TODO Auto-generated method stub
                WechatLogin wechatLogin = new WechatLogin();
                wechatLogin.setMobilephone(mobile);
                wechatLogin.setOpenid(openid);
                wechatLogin.setStatus(status);
                loginDao.updateWechatLogin(wechatLogin);
                bool = true;
            }
        }
        return bool;
    }


    /**
     * 添加微信信息  更新收款员信息
     *
     * @param mobile
     * @param openid
     * @return zhenliu  2017-09-20
     */
    @Override
    @Transactional
    public int saveUserInfoUpdateCashierState(String mobile, String openid) {

        UserWechatInfo userWechatInfo = uwiService.gainUserWechatInfo(openid);
        if (userWechatInfo != null && StringUtil.isNotEmpty(userWechatInfo.getOpenid())) {
            UserWechatInfo wechat = uwiService.findOneByOpenidInUserWX(openid);
            if (wechat != null&&StringUtil.isNotEmpty(wechat.getOpenid())) {
                uwiService.updateWechatUserInfo(userWechatInfo);
            }else {
                userWechatInfoService.addWechatUserInfo(userWechatInfo);
            }
        }
        //更新收款员表
        return cashiersService.updateCashierState("1", mobile);
    }


    @Override
    public void updateWechatLoginByOpenid(int status, String mobile, String openid) {
        WechatLogin wechatLogin = new WechatLogin();
        wechatLogin.setMobilephone(mobile);
        wechatLogin.setOpenid(openid);
        wechatLogin.setStatus(status);
        loginDao.updateWechatLoginByOpenid(wechatLogin);
    }

    @Override
    public String getValidCode(String mobile) {
        String mobile_code = RandomStringUtils.randomNumeric(6);
        logger.info("mobile_code==" + mobile_code);
        String tpl_id = "37654";
        try {
            String content = URLEncoder.encode("#code#=" + mobile_code + "&#company#=道合聚盈", "utf-8");
            jedisExe.setValue(JedisKeyPrefix.JEDIS_KEY_PREFIX_MOBILE, mobile, mobile_code, 60);
            String result = HttpUtils.getValidCode(mobile, tpl_id, content);
            JSONObject object = JSONObject.fromObject(result);
            logger.info("发送短信验证码返回结果：" + result);

            if (object != null && object.getInt("error_code") == 0) { // 发送成功
                jedisExe.setValue(JedisKeyPrefix.JEDIS_KEY_PREFIX_MOBILE, mobile,
                        mobile_code, 60);
                logger.info("sucess");
                return "ok";
            } else {
                logger.info("验证码发送失败===:"+object);
                return "验证码发送失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("验证码发送失败：" + e.getMessage());
            return "验证码发送失败";
        }
    }

}
